YUI.add('treeview', function (Y) {
	
	var YAHOO = Y.YUI2;
	
	
    function TreeView(config) {
    	TreeView.superclass.constructor.apply(this, arguments);
    }
    
    
    TreeView.NAME = 'treeview';
    
    
    Y.extend(TreeView, Y.View, {
    	container: Y.one('#' + TreeView.NAME),
    	
    	tree: null,
    	
    	events: {
    		
    	},
    	
    	initializer: function () {
    		
    	},
    	
    	render: function () {
    		Y.io('.sp/toc.json', {
	    	    context: this,
	    		on : {
	    	    	complete : this.onTOCComplete
	    		}
    		});
    		
    		return this;
    	},
    	
    	onTOCComplete: function (transaction, response, parameter) {
        	this.tree = new YAHOO.widget.TreeView('tree', Y.JSON.parse(response.responseText));

        	// On tree node click event
        	this.tree.subscribe('clickEvent', function (o) {
        		// Update the MainModel which will trigger the rendering of other view.
        		this.model.set('pageid', o.node.data.pageid);
        	}, this, true);
        	
    		Y.io('.sp/index.json', {
	    	    context: this,
	    		on : {
	    	    	complete : this.onIndexComplete
	    		}
    		});        	
    	},
    	
    	onIndexComplete: function (transaction, response, parameter) {
    		var indexArray = Y.JSON.parse(response.responseText),
    			indexMap = [],
    			cnt;
    		
    		// Create a associative array for faster access of page path.
    		for (cnt = 0; cnt < indexArray.length; cnt++) {
    			indexMap[indexArray[cnt].pageid] = indexArray[cnt].path; 
    		}
    		
    		// Keep the page index in the model
    		this.model.set('indexMap', indexMap);
    		
    		this.tree.render();
    	}
    	
    });
    

    Y.namespace('srcprojector').TreeView = TreeView;
    

}, '0.1.0', {requires: ['view', 'io-base', 'json-parse']});